import { EmailSystemConfig } from '../services/EmailOrchestrator';

/**
 * Email System Configuration
 * Centralized configuration for the entire email system
 */
export const emailSystemConfig: EmailSystemConfig = {
  smtp: {
    host: process.env.SMTP_HOST || 'smtp.mailgun.org',
    port: parseInt(process.env.SMTP_PORT || '587'),
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: process.env.SMTP_USER || '',
      pass: process.env.SMTP_PASS || ''
    },
    pool: true,
    maxConnections: parseInt(process.env.SMTP_MAX_CONNECTIONS || '5'),
    maxMessages: parseInt(process.env.SMTP_MAX_MESSAGES || '100'),
    rateDelta: parseInt(process.env.SMTP_RATE_DELTA || '1000'),
    rateLimit: parseInt(process.env.SMTP_RATE_LIMIT || '10')
  },
  supabase: {
    url: process.env.SUPABASE_URL || '',
    key: process.env.SUPABASE_ANON_KEY || ''
  },
  baseUrl: process.env.BASE_URL || 'https://arxiv-hub.com',
  compliance: {
    canSpamEnabled: process.env.CAN_SPAM_ENABLED !== 'false',
    gdprEnabled: process.env.GDPR_ENABLED !== 'false',
    doubleOptInEnabled: process.env.DOUBLE_OPT_IN_ENABLED !== 'false'
  },
  logging: {
    level: process.env.LOG_LEVEL || 'info',
    format: process.env.LOG_FORMAT || 'json'
  }
};

/**
 * SMTP Provider Configurations
 * Pre-configured settings for popular email providers
 */
export const smtpProviders = {
  mailgun: {
    host: 'smtp.mailgun.org',
    port: 587,
    secure: false,
    rateDelta: 1000,
    rateLimit: 10
  },
  sendgrid: {
    host: 'smtp.sendgrid.net',
    port: 587,
    secure: false,
    rateDelta: 1000,
    rateLimit: 100
  },
  amazonses: {
    host: 'email-smtp.us-east-1.amazonaws.com',
    port: 587,
    secure: false,
    rateDelta: 1000,
    rateLimit: 14  // Amazon SES default
  },
  postmark: {
    host: 'smtp.postmarkapp.com',
    port: 587,
    secure: false,
    rateDelta: 1000,
    rateLimit: 300
  },
  mailchimp: {
    host: 'smtp.mandrillapp.com',
    port: 587,
    secure: false,
    rateDelta: 1000,
    rateLimit: 10
  }
};

/**
 * Email Template Configuration
 */
export const templateConfig = {
  // Base template paths
  templatePaths: {
    base: 'templates/',
    components: 'templates/components/',
    layouts: 'templates/layouts/'
  },
  
  // Default template settings
  defaults: {
    fromName: 'ArXiv Research Hub',
    replyTo: 'noreply@arxiv-hub.com',
    charset: 'utf-8',
    textEncoding: 'quoted-printable'
  },
  
  // Template types and their configurations
  templates: {
    daily_digest: {
      subject: '📚 Your Daily ArXiv Digest - {{summary.totalPapers}} New Papers',
      preheader: 'Discover today\'s most relevant research papers',
      maxPapers: 10,
      includeCategories: true,
      includeAbstracts: true
    },
    weekly_summary: {
      subject: '📊 Weekly Research Roundup - {{summary.timeRange}}',
      preheader: 'Your week in research highlights',
      maxPapers: 15,
      includeTrending: true,
      includeStats: true
    },
    paper_alert: {
      subject: '🔔 New Paper Alert: {{papers.0.title}}',
      preheader: 'A highly relevant paper has been published',
      immediateDelivery: true,
      includeFullAbstract: true
    },
    welcome_series_1: {
      subject: '🎉 Welcome to ArXiv Research Hub!',
      preheader: 'Your journey to better research discovery starts here',
      delay: 0,
      includeOnboarding: true
    },
    welcome_series_2: {
      subject: '📖 Discover Your Research Interests',
      preheader: 'Let\'s personalize your experience',
      delay: 2, // days
      includePreferenceSetup: true
    },
    welcome_series_3: {
      subject: '🚀 Maximize Your Research Efficiency',
      preheader: 'Pro tips for getting the most out of ArXiv Research Hub',
      delay: 7, // days
      includeTips: true
    }
  }
};

/**
 * Personalization Configuration
 */
export const personalizationConfig = {
  // Relevance scoring weights
  scoringWeights: {
    categoryMatch: 0.4,
    keywordMatch: 0.3,
    authorMatch: 0.2,
    citationScore: 0.1,
    recencyBoost: 0.05,
    viewHistory: 0.15
  },
  
  // Personalization thresholds
  thresholds: {
    minRelevanceScore: 0.3,
    highRelevanceThreshold: 0.8,
    instantAlertThreshold: 0.9,
    maxRecommendationsPerDigest: 20
  },
  
  // User profiling settings
  profiling: {
    minInteractionsForPersonalization: 5,
    interactionDecayRate: 0.1, // How quickly old interactions lose weight
    categoryDiversityWeight: 0.2,
    adaptiveLearningRate: 0.05
  }
};

/**
 * Scheduling Configuration
 */
export const schedulingConfig = {
  // Default schedules
  defaultSchedules: {
    dailyDigest: {
      time: '09:00',
      timezone: 'UTC',
      daysOfWeek: [1, 2, 3, 4, 5] // Monday to Friday
    },
    weeklyDigest: {
      dayOfWeek: 1, // Monday
      time: '10:00',
      timezone: 'UTC'
    }
  },
  
  // Job processing settings
  jobProcessing: {
    batchSize: 100,
    delayBetweenBatches: 1000, // ms
    maxRetries: 3,
    retryDelay: 5000, // ms
    jobTimeout: 300000 // 5 minutes
  },
  
  // Rate limiting
  rateLimits: {
    emailsPerMinute: 100,
    emailsPerHour: 5000,
    emailsPerDay: 50000,
    emailsPerUserPerDay: 5
  }
};

/**
 * Compliance Configuration
 */
export const complianceConfig = {
  // CAN-SPAM settings
  canSpam: {
    senderInfo: {
      name: 'ArXiv Research Hub',
      address: {
        street: '123 Research Avenue',
        city: 'San Francisco',
        state: 'CA',
        zipCode: '94102',
        country: 'United States'
      }
    },
    optOutProcessing: {
      maxProcessingTime: 10, // business days
      honorsReplyUnsubscribe: true,
      includesPostalAddress: true
    }
  },
  
  // GDPR settings
  gdpr: {
    dataRetention: {
      emailLogs: 730, // 2 years
      userInteractions: 1095, // 3 years
      consentRecords: 2555, // 7 years (legal requirement)
      analyticsData: 365 // 1 year
    },
    dataProcessing: {
      legalBasis: 'consent',
      purposes: [
        'email_marketing',
        'service_provision',
        'analytics',
        'personalization'
      ],
      dataCategories: [
        'email_address',
        'research_preferences',
        'interaction_history',
        'device_information'
      ]
    },
    subjectRights: {
      responseTimeLimit: 30, // days
      dataExportFormat: 'json',
      automaticDeletion: true
    }
  },
  
  // Double opt-in settings
  doubleOptIn: {
    confirmationTimeframe: 24, // hours
    reminderSchedule: [12, 23], // hours after initial confirmation
    cleanupExpiredTokens: 72 // hours
  }
};

/**
 * Tracking and Analytics Configuration
 */
export const trackingConfig = {
  // Tracking settings
  tracking: {
    enableOpenTracking: true,
    enableClickTracking: true,
    enableUnsubscribeTracking: true,
    pixelTrackingDomain: process.env.TRACKING_DOMAIN || 'track.arxiv-hub.com',
    linkTrackingDomain: process.env.LINK_TRACKING_DOMAIN || 'click.arxiv-hub.com'
  },
  
  // Analytics retention
  dataRetention: {
    rawEvents: 365, // days
    aggregatedMetrics: 1095, // 3 years
    userEngagementData: 730, // 2 years
    campaignResults: 2190 // 6 years
  },
  
  // Performance monitoring
  monitoring: {
    alertThresholds: {
      bounceRate: 5.0, // percent
      spamComplaintRate: 0.1, // percent
      deliveryFailureRate: 2.0, // percent
      queueBacklog: 1000 // number of jobs
    },
    healthChecks: {
      interval: 60000, // 1 minute
      timeout: 30000, // 30 seconds
      retries: 3
    }
  }
};

/**
 * A/B Testing Configuration
 */
export const abTestingConfig = {
  // Test settings
  testing: {
    defaultSplitRatio: 50, // 50/50 split
    minSampleSize: 100,
    maxTestDuration: 30, // days
    confidenceLevel: 0.95,
    significanceThreshold: 0.05
  },
  
  // Metrics to track
  metrics: {
    primary: ['open_rate', 'click_rate'],
    secondary: ['conversion_rate', 'unsubscribe_rate', 'time_to_open'],
    engagement: ['email_forwards', 'social_shares', 'time_spent_reading']
  },
  
  // Auto-winner selection
  autoWinner: {
    enabled: true,
    minimumRunTime: 7, // days
    requiredConfidence: 0.95,
    minimumImprovement: 5 // percent
  }
};

/**
 * Security Configuration
 */
export const securityConfig = {
  // Token security
  tokens: {
    unsubscribeTokenExpiry: 30 * 24 * 60 * 60 * 1000, // 30 days in ms
    trackingTokenExpiry: 90 * 24 * 60 * 60 * 1000, // 90 days in ms
    confirmationTokenExpiry: 24 * 60 * 60 * 1000, // 24 hours in ms
    secretRotationInterval: 30 * 24 * 60 * 60 * 1000 // 30 days in ms
  },
  
  // Email security
  emailSecurity: {
    enableDKIM: true,
    enableSPF: true,
    enableDMARC: true,
    requireTLS: true,
    validateRecipients: true
  },
  
  // API security
  apiSecurity: {
    rateLimiting: {
      windowMs: 15 * 60 * 1000, // 15 minutes
      maxRequests: 100,
      trustProxy: true
    },
    allowedOrigins: [
      'https://arxiv-hub.com',
      'https://app.arxiv-hub.com',
      'https://admin.arxiv-hub.com'
    ]
  }
};

/**
 * Export all configurations
 */
export const emailConfig = {
  system: emailSystemConfig,
  templates: templateConfig,
  personalization: personalizationConfig,
  scheduling: schedulingConfig,
  compliance: complianceConfig,
  tracking: trackingConfig,
  abTesting: abTestingConfig,
  security: securityConfig,
  smtpProviders
};